<?php
class robotsAction extends BackendAction {
	private $_tbconfig = null;
	public function _initialize() {
        parent::_initialize();
    $this->tqkuid=C('yh_app_kehuduan');
	$tkapi=F('tqkapi/api');
	if(false ===$tkapi){
		$this->tqkapi = 'http://api.tuiquanke.com';
		}else{
		$this->tqkapi = $tkapi;
	}
	
$appkey=trim(C('yh_gongju'));
if(!$appkey){
$this->error('请到 站点设置  填写通行密钥',U('setting/index'));	
}
	
if(!$this->tqkuid){
$map=array(
'appkey'=>$appkey
);

$apiurl='http://api.tuiquanke.cn/getappkey';
$result=$this->_curl($apiurl,$map);
$result=json_decode($result,true);
if($result && $result['status']==1){
$mod=M('setting');
$where=array(
'name'=>'app_kehuduan'
);
$datat=array(
'data'=>$result['tqkuid']
);
$mod->where($where)->save($datat);
$this->tqkuid=$result['tqkuid'];
}else{

$this->error('无法获取数据，请联系推券客客服。');	
	
}
}	
	
    }
    public function index(){
				$where['status'] = 1;
				$where['http_mod'] = 0;
				$robots = M('robots')->where($where)->order('ordid asc')->select();
			$this->assign('list', $robots);
    	$this->display();
    }
    
    
    
    
    
public function tuiquanke()
{
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/tuiquanke_collect.php';
$ret=opcache_invalidate($dir,TRUE);
}
 $tuiquanke_collect = F('tuiquanke_collect');
if(!$tuiquanke_collect || $tuiquanke_collect===false){
$page = 1;
}else{
$page =$tuiquanke_collect['page'];
 }

	    $result_data = $this->tuiquanke_collect($page);
	    if($result_data){
	    $this->assign('result_data', $result_data);
	    $resp = $this->fetch('collect');
	    $this->ajaxReturn($page==150?0:1, $page==150?'采集完成或者没有新数据了':$page+1, $resp);
	    }
	}
	
private function tuiquanke_collect($page)
{
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/tuiquanke_collect.php';
$ret=opcache_invalidate($dir,TRUE);
}
$tuiquanke_collect = F('tuiquanke_collect');
if(!$tuiquanke_collect || $page==1){
            $coll=0;
            $totalcoll = 0;
        }
        else{
           $coll = $tuiquanke_collect['coll'];
           $totalcoll = $tuiquanke_collect['totalcoll'];
  }
  
$file = FTX_DATA_PATH.'start.txt';
        if(!file_exists($file)){
            return false;
        }
$startId = file_get_contents($file);
        if(!$startId){
            $startId = 0;
        }
$map=array(
		'start'=>$startId,
		'pagesize'=>500,
		'time'=>time(),
		'tqk_uid'=>$this->tqkuid
);
$token=$this->create_token(trim(C('yh_gongju')),$map);
$map['token']=$token;
$url = $this->tqkapi.'/gettbitems';    
$result = $this->_curl($url,$map);
 $json = json_decode($result, true);
		 $PID= $json['pid'];
		 $json = $json['result'];
		 $count=count($json);
      if($count>0){
       $t=0;
       $coll=0;
      foreach ($json as $key => $val){
        if(C('yh_site_secret')==1 && false === strpos($attach, 'https://')){
		$pic_url=str_replace("http://","https://",$val['pic_url']);
		}else{
		$pic_url=$val['pic_url'];
		}
        $raw= array(
                    'link'=>$val['link'],
                    'pic_url'=>$pic_url,
                    'title'=>$val['title'],
                    'tags'=>$val['tags'],
                    'coupon_start_time'=>$val['coupon_start_time'],
                    'coupon_end_time'=>$val['coupon_end_time'],
                    'ali_id'=>$val['ali_id'],
                    'cate_id'=>$val['cate_id'],
                    'shop_name'=>$val['shop_name'],
                    'shop_type'=>$val['shop_type'],
                    'ems'=>$val['ems'],
                    'num_iid'=>$val['num_iid'],
                    'volume'=>$val['volume'],
                    'commission'=>$val['commission'],
                    'commission_rate'=>$val['commission_rate'],
                    'tk_commission_rate'=>$val['tk_commission_rate'],
                    'sellerId'=>$val['sellerId'],
                    'nick'=>$val['nick'],
                    'mobilezk'=>0,
                    'area'=>0,
                    'hits'=>0,
                    'tk'=>$val['tk'],
                    'price'=>$val['price'],
                    'coupon_price'=>$val['coupon_price'],
                    'coupon_rate'=>$val['coupon_rate']?$val['coupon_rate']:0,
                    'coupon_type'=>$val['coupon_type'],
                    'intro'=>$val['intro'],
                    'desc'=>$val['desc'],
                    'isq'=>'1',
                    'zc_id'=>$val['zc_id'],
                    'quan'=>$val['quan'],
                    'Quan_id'=>$val['Quan_id'],
                    'Quan_condition'=>0,
                    'Quan_surplus'=>$val['Quan_surplus']?$val['Quan_surplus']:0,
                    'Quan_receive'=>$val['Quan_receive']?$val['Quan_receive']:0,
                    'is_commend'=>$val['is_commend']?$val['is_commend']:0,
                    'recid'=>1,
                    'quanurl'=>'https://uland.taobao.com/coupon/edetail?activityId='.$val['Quan_id'].'&itemId='.$val['num_iid'].'&pid='. $PID .'',
                );
                 $startId = $val['up_time'];
                  $res= $this->_ajax_yh_publish_insert($raw);
                   $coll++;
                  $totalcoll++;
                  $t++;
            }
          file_put_contents($file, $startId);
        }else{
        $page=149;
        $msg="失败！";
        }

        $result_data['p']	 = $page;
        $result_data['msg']	 = $msg;
        $result_data['coll']		= $count;
        $result_data['totalcoll']	= $totalcoll;
        $result_data['totalnum']	=   $count;
        $result_data['thiscount']	= count($item);
        $result_data['times']		= time();
        F('tuiquanke_collect', array(
            'coll'=>$coll, 
            'page'=>$page==150?0:$page+1,
            'totalcoll'=>$totalcoll
        ));
        return $result_data;


	}
	
   private function _ajax_yh_publish_insert($item)
    {
        $result = D('items')->ajax_yh_publish($item);
        return $result;
    }   
    
    
public function collect(){
		$id	= I('id','','intval');
		$auto	= I('auto',0,'intval');
		$p		= I('p',1,'intval');

$where=array(
'id'=>$id
);
$date = M('robots')->field('tb_cid',true)->where($where)->find();
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/robot_setting.php';
$ret=opcache_invalidate($dir,TRUE);
}
F('robot_setting', $date);
		
if($date){
	
if($date['http_mode'] == '0'){
	
if ($p > $date['page']) {
		
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/totalcoll.php';
$ret=opcache_invalidate($dir,TRUE);
}
					F('totalcoll', NULL);
					$this->ajaxReturn(0, '已经采集完成'.$date['page'].'页！请返回，谢谢');
}
				
               $result_data = $this->api_collect($date,$p);
				$this->assign('result_data', $result_data);
			    $resp = $this->fetch('collect');
				if($result_data['coll'] <= 0){
				    $this->ajaxReturn(0, '已经采集完成！请返回，谢谢',$resp);
				}
			
				$this->ajaxReturn(1, '', $resp);
			}
			
		}else{
			$this->ajaxReturn(0, 'error');
		}
	}

public function api_collect($date,$p)
{
if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/totalcoll.php';
$dir2=$basedir.'/data/Runtime/Data/robots_time.php';
$ret=opcache_invalidate($dir,TRUE);
$ret=opcache_invalidate($dir2,TRUE);
}
M('robots')->where(array('id'=>$date['id']))->save(array('last_page'=>$p,'last_time'=>time()));
		if (false === $totalcoll = F('totalcoll')) {
			$totalcoll = 0;
		}
		if (false === $robots_time = F('robots_time')) {
			$robots_time = time();
			F('robots_time', time());
		}
		 $cate = array();
		 if($date['cate_id']){
		    $cate = M('items_cate')->field('ali_id,id')->where(array('id'=>$date['cate_id']))->find();
		 }
$appkey=trim(C('yh_taobao_appkey'));
$appsecret=trim(C('yh_taobao_appsecret'));
$apppid=trim(C('yh_taobao_pid'));
$apppid=explode('_', $apppid);
$AdzoneId=$apppid[3];
if(!empty($appkey) && !empty($appsecret) && !empty($AdzoneId)){
vendor('taobao.TopSdk');
$c = new \TopClient();
$c->appkey = $appkey;
$c->secretKey = $appsecret;
$req = new \TbkDgMaterialOptionalRequest();
$req->setPageSize("100");
$req->setPageNo("".$p."");
$req->setPlatform("1");
$req->setIsOverseas("true");
$req->setCat($date['keyword']);
$req->setHasCoupon("true");
$req->setAdzoneId($AdzoneId);
$resp = $c->execute($req);
$resp = json_decode(json_encode($resp), true);
$datares=$resp['result_list']['map_data'];
}

if($datares){		
	$t=0;
	  $coll=0;
	$now=time();
		foreach ($datares as $key => $val){
		$link = 'https://item.taobao.com/item.htm?id=' . $val['num_iid'];
		if(!empty($val['coupon_id']) && !empty($val['seller_id'])){ 
            $receive = $val['coupon_total_count'];
            $preg1 = '/减(.+?)元/is';
			preg_match($preg1, $val['coupon_info'], $allhtml1);
			$coupon_price=$allhtml1[1];
            $pic_url = str_replace('http://', 'https://', $val['pict_url']);
            $pic_url = str_replace('_400x400', '', $pic_url);
		    $raw = array(
		        'link'=>$link,
		        'click_url'=>'',
		        'pic_url'=>$pic_url,
		        'title'=>$val['title'],
		        'coupon_start_time'=>NOW_TIME,
		        'add_time'=>strtotime(date('Y-m-d H:i:s')),
		        'coupon_end_time'=>strtotime($val['coupon_end_time']),
		        'ali_id'=>$cate['ali_id'],
		        'cate_id'=>$cate['id'],
		        'shop_name'=>$val['shop_title'],
		        'shop_type'=>$val['user_type']==1?'B':'C',
		        'ems'=>'',
		        'num_iid'=>$val['num_iid'],
		        'volume'=>$val['volume'],
		        'commission'=>$val['commission_rate'],
		        'tuisong'=>1,
		        'pass'=>1,
		        'status'=>'underway',
		        'isshow'=>1,
		        'commission_rate'=>$val['commission_rate'],
		        'tk_commission_rate'=>'',
		        'sellerId'=>$val['seller_id'],
		        'nick'=>'0',
                'area'=>0,
		        'mobilezk'=>0,
		        'hits'=>0,
		        'price'=>$val['zk_final_price'],
		        'coupon_price'=>$val['zk_final_price']-$coupon_price,
		        'coupon_rate'=>intval(($val['zk_final_price']-$coupon_price)/$val['zk_final_price']*100*100),
		        'intro'=>'',
		        'up_time'=>$now+$t,
		        'desc'=>'',
		        'isq'=>'1',
		        'quanurl'=>'',
		        'quan'=>$coupon_price,
		        'Quan_id'=>$val['coupon_id'],
		        'Quan_condition'=>0,
		        'Quan_surplus'=>$receive*10,
		        'Quan_receive'=>$receive
		    );
            $res= $this->_ajax_yh_publish_insert($raw);
             $coll++;
             $totalcoll++;
            	}


		    $thiscount++;
			$t++;
		}
		



if(function_exists('opcache_invalidate')){
$basedir = $_SERVER['DOCUMENT_ROOT']; 
$dir=$basedir.'/data/Runtime/Data/totalcoll.php';
$ret=opcache_invalidate($dir,TRUE);
}
F('totalcoll',$totalcoll);
if($sus=='no'){
 $p = $date['page']+1; 
}

}else{
$p=499;
}
		
		$result_data['p']			= $p;
		$result_data['msg']			= $msg;
		$result_data['coll']		    = $coll;
		$result_data['totalcoll']	= $totalcoll;
		$result_data['totalnum']  	=   $totalnum;
		$result_data['thiscount']	= $thiscount;
		$result_data['times']		= lefttime(time()-$robots_time);
		return $result_data;
		
		
}  
    
protected function create_token($key,$data=array()){
$ServerToken='';
foreach($data as $k=>$v){
	$ServerToken.=md5($v);
}
$ServerToken=md5($ServerToken .'_'.$key);
return $ServerToken;
}    
    
 protected function _curl($url, $data = array(), $is_post = false, $cookie = null, $referer = null)
    {
        set_time_limit(10);
        $curl = curl_init();
        if($data && $is_post == false){
            $url .= '?' . http_build_query($data);
        }
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //
		curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //
		curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if($is_post){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        if($cookie){
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        if($referer){
            curl_setopt($curl, CURLOPT_REFERER, $referer);
        }
       curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5' );  
        curl_setopt($curl, CURLOPT_TIMEOUT,10);
        $result = curl_exec($curl);
		//var_dump(curl_error($curl));
        curl_close($curl);
        if (empty($result)) {
            $result = false;
        }
        
        return $result;
    }
    

}